<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-back" @tap="goBack">
          <uni-icons type="left" size="20" color="#333"></uni-icons>
        </view>
        <view class="message-tabs">
          <view class="tab" :class="{ active: true }" @click="navigateToPage('/pages/user/message/chat')">
            私信
          </view>
          <view class="tab" :class="{ active: false }" @click="navigateToPage('/pages/user/message/system')">
            系统消息
          </view>
        </view>
      </view>
    </view>

    <!-- 联系人列表 -->
    <scroll-view 
      class="contact-list" 
      scroll-y 
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <view 
        class="contact-item" 
        v-for="contact in contacts" 
        :key="contact.userId"
        @tap="goChatDetail(contact)"
      >
        <!-- 用户头像 -->
        <image 
          class="avatar" 
          :src="contact.avatar || '/static/images/default-avatar.jpg'" 
          mode="aspectFill"
        ></image>
        
        <!-- 消息预览 -->
        <view class="preview">
          <view class="user-info">
            <text class="nickname">{{ contact.nickname }}</text>
            <text class="time">{{ formatTime(contact.lastMessageTime) }}</text>
          </view>
          <view class="message-preview">
            <text class="content">{{ contact.lastMessage }}</text>
            <view class="unread" v-if="contact.unreadCount > 0">
              {{ contact.unreadCount > 99 ? '99+' : contact.unreadCount }}
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus"></uni-load-more>
    </scroll-view>
  </view>
</template>

<script>
import { formatTime } from '@/utils/date'

export default {
  data() {
    return {
      contacts: [],
      page: 1,
      pageSize: 20,
      loadMoreStatus: 'more',
      isRefreshing: false,
      hasMore: true
    }
  },

  onLoad() {
    this.loadContacts()
  },

  methods: {
    formatTime,

    // 页面导航方法
    navigateToPage(path) {
      uni.navigateTo({
        url: path
      })
    },

    // 加载联系人列表
    async loadContacts(refresh = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        if (refresh) {
          this.page = 1
          this.contacts = []
          this.hasMore = true
        }

        const res = await this.$api.message.chat.getContacts({
          pageNum: this.page,
          pageSize: this.pageSize
        })

        if (res.code === 200 && res.data) {
          const { records, total } = res.data
          
          // 格式化联系人数据
          const formattedContacts = records.map(contact => ({
            userId: contact.userId,
            nickname: contact.nickname || '未知用户',
            avatar: contact.avatar || '/static/images/default-avatar.jpg',
            lastMessage: contact.lastMessage || '',
            lastMessageTime: contact.lastMessageTime,
            unreadCount: contact.unreadCount || 0
          }))

          this.contacts = refresh ? formattedContacts : [...this.contacts, ...formattedContacts]
          this.hasMore = this.contacts.length < total
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
          this.page++
        }
      } catch (error) {
        console.error('加载联系人列表失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (refresh) {
          this.isRefreshing = false
        }
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      await this.loadContacts(true)
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadContacts()
      }
    },

    // 跳转到聊天详情页
    goChatDetail(contact) {
      uni.navigateTo({
        url: `/pages/user/message/chat-detail?userId=${contact.userId}&nickname=${encodeURIComponent(contact.nickname)}&avatar=${encodeURIComponent(contact.avatar)}`
      })
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.chat-container {
  min-height: 100vh;
  background-color: #fff;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  
  .nav-content {
    position: relative;
    padding-top: var(--status-bar-height);
    
    .nav-back {
      position: absolute;
      left: 30rpx;
      top: calc(var(--status-bar-height) + 24rpx);
      z-index: 1;
      padding: 20rpx;
    }
    
    .message-tabs {
      display: flex;
      justify-content: center;
      padding: 20rpx 120rpx;
      
      .tab {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        color: #666;
        position: relative;
        padding: 20rpx 0;
        
        &.active {
          color: #333;
          font-weight: bold;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background-color: #333;
            border-radius: 2rpx;
          }
        }
      }
    }
  }
}

.contact-list {
  padding: 20rpx;
  padding-top: 128rpx;
  height: calc(100vh - 128rpx);
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f5f5f5;
  
  .avatar {
    width: 96rpx;
    height: 96rpx;
    border-radius: 48rpx;
    margin-right: 24rpx;
  }
  
  .preview {
    flex: 1;
    overflow: hidden;
    
    .user-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8rpx;
      
      .nickname {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }
      
      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .message-preview {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .content {
        flex: 1;
        font-size: 28rpx;
        color: #666;
        @include text-ellipsis;
      }
      
      .unread {
        min-width: 36rpx;
        height: 36rpx;
        padding: 0 12rpx;
        background-color: #ff5500;
        border-radius: 18rpx;
        color: #fff;
        font-size: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 16rpx;
      }
    }
  }
  
  &:active {
    background-color: #f8f8f8;
  }
}
</style> 